package 剑指Offer;

import java.util.*;

public class Offer32I_从上到下打印二叉树 {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }


    public int[] levelOrder(TreeNode root) {
        if (root == null) {
            return new int[]{};
        }

        Queue<TreeNode> q = new LinkedList<>(); // 核心数据结构

        //  保存结果
        List<Integer> ans = new ArrayList<>();

        q.add(root);
        while (!q.isEmpty()) {
            int size = q.size();
            for (int i = 0; i < size; i++) {
                TreeNode cur = q.poll();
                ans.add(cur.val);

                //找到cur的相邻节点
                if (cur.left != null) {
                    q.add(cur.left);
                }
                if (cur.right != null) {
                    q.add(cur.right);
                }
            }
        }
        int[] res = new int[ans.size()];
        for (int i = 0; i < ans.size(); i++) {
            res[i] = ans.get(i);
        }
        return res;
    }
}
